/******************************************************
 Project:				PCSync
 Author:				Jean-Philippe
 File name:				Authenticator.java
 Date created:			2012-09-30
 Date last modified:	2012-09-30
 *******************************************************
 Modification History
 *******************************************************
 2012-09-30		Initial version.
 ******************************************************/
package pcsync.server;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Hashtable;

import pcsync.Config;
import pcsync.Message;
import pcsync.MessageAuthenticate;
import pcsync.MessageHandler;

/**
 * @author Jean-Philippe
 *
 */
public class Authenticator extends MessageHandler
{
	private static Authenticator instance;
	private Hashtable<String,String> users;
	
	private Authenticator()
	{
		logger.debug("Authenticator initializing");
		loadFromFile(Config.USER_CREDENTIALS_FILE);
	}
	
	public static Authenticator getInstance()
	{
		if( instance == null )
		{
			instance = new Authenticator();
		}
		
		return instance;
	}

	/* (non-Javadoc)
	 * @see pcsync.MessageHandler#handle(pcsync.Message)
	 */
	@Override
	public void handle(Message message)
	{
		MessageAuthenticate msgAuth = (MessageAuthenticate)message;
		logger.debug("Authenticating login by user " + msgAuth.getUsername());
		String password = this.users.get(msgAuth.getUsername());
		if( password != null )
		{
			if( password.equals(msgAuth.getPassword()) )
			{
				logger.info("User '" + msgAuth.getUsername() + "' authenticated");
			}
			else
			{
				logger.info("Invalid password for user '" + msgAuth.getUsername() + "'");
			}
		}
		else
		{
			logger.info("Invalid username: '" + msgAuth.getUsername() + "'");
		}
	}
	
	private boolean loadFromFile(String strFile)
	{
		this.users = new Hashtable<String,String>();
		
		try
		{
			// Open the file
			logger.info("Loading user credentials database " + strFile);
			FileInputStream fstream = new FileInputStream(strFile);
			
			// Get the object of DataInputStream
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String strLine;
			
			//Read File Line By Line
			while ((strLine = br.readLine()) != null)
			{
				String[] uandp = strLine.split(":");
				this.users.put(uandp[0], uandp[1]);
				logger.debug("Added user '" + uandp[0] + "' to the list of authorized users");
			}
			
			//Close the input stream
			in.close();
		}
		catch (Exception e)
		{
			//Catch exception if any
			System.err.println("Error: " + e.getMessage());
			logger.error("Unable to load user credentials database \""+strFile+"\"");
			return false;
		}
		
		return true;
	}
}
